<?php
namespace app\applet\controller;

use app\applet\model\HouseKeeper;
use app\common\model\SendSms;
use app\common\model\TokenCheck;
use app\manage\model\AdminUser;
use app\manage\model\Code;
use app\manage\model\TenantManagement;
use Template\WeChat;
use think\Controller;
use think\Db;
use think\Request;
use think\Validate;

class UserLogin extends Controller {
    private $token_check;
    public function __construct(Request $request = null)
    {
//        parent::__construct($request);
        $this->token_check = new TokenCheck();
    }

    /**
     * @throws \Exception
     */
    public function login()
    {
        $get = input();
        //获取session_key
        $params['appid'] = config('applet')['tenant']['appid'];
        $params['secret'] = config('applet')['tenant']['secret'];
        $params['js_code'] = define_str_replace($get['code']);
        $params['grant_type'] = 'authorization_code';
        $http_key = httpCurl('https://api.weixin.qq.com/sns/jscode2session', $params, 'GET');
        $session_key = json_decode($http_key, true);
        if (!empty($session_key['session_key'])) {
            /**
             * 验证微信是否绑定手机号
             */
            $model = new HouseKeeper();
            $detail = $model->uniqueness($get['tel']);
            if (empty($detail)) {
                $detail = $model->detailOpenId($session_key['openid']);
                if (!empty($detail)) {
                    if ($detail['tel'] != $get['tel']) {
                        returnJson(-2010,"微信已绑定其他手机号，请登录绑定手机号")->send();die;
                    }
                }
            }


            /**
             * 验证用户状态
             */
            $model = new HouseKeeper();
            $detail = $model->uniqueness($get['tel']);
            if (!empty($detail)) {
                if ($detail['status'] == 3) {
                    returnJson(-2010,"该账号已被删除")->send();die;
                } elseif ($detail['status'] == 2) {
                    returnJson(-2010,"该账号已被禁用")->send();die;
                }
            }

            /**
             * 检测验证码
             */
            $model = new Code();
            $code = $get['verification_code'];
            $detail = $model->detailtel($get['tel']);
            if (empty($detail)) {
                returnJson(-2010,"请先发送验证码")->send();die;
            }
            if ((time() - $detail['create_time']) > (30 * 60)) {
                returnJson(-2010,"验证码过期")->send();die;
            }
            if ($detail['is_use'] == 1) {
                returnJson(-2010,"验证码已被使用")->send();die;
            }
            if ($detail['code'] !== $code) {
                returnJson(-2011,"验证码错误")->send();die;
            }
            $data['is_use'] = 1;
            $model->m_update($detail['code_id'], $data);
            unset($data['is_use']);

            /**
             * 1、查找是否已加入数据库
             * 2、若未加，则插入本地数据库
             */

            $data['open_id'] = $session_key['openid'];
            $data['key'] = $session_key['session_key'];
            $data['tel'] = $get['tel'];
            $data['name'] = $get['nickName'];
            $data['sex'] = $get['gender'];
            $data['icon'] = $get['avatarUrl'];
            $data['create_time'] = time();
            $data['update_time'] = time();
            $result = $this->insert($data);

            /**
             * 通过电话查询租客表是否已有相关信息，若存在，则将id绑定
             */
            $model = new TenantManagement();
            $detail = $model->phone($data['tel']);
            if ($detail !== null) {
                $model->m_update($detail['tenant_id'], ['tenant_user_id'=>$result[0]]);
            }

            /**
             * 获取公众号openid
             */
            $subscription_code = $get['wxcode'];
            $WeChat = new  \Template\Wechat();
            $WeChat->getUserInfo($data['tel'], $subscription_code);

            $model = new HouseKeeper();
            $detail = $model->detail($result[0]);
            $data_qd = [
                'name' => $detail['name'],
                'icon'=> $detail['icon']
            ];
            returnJson(200,'操作成功', $this->token_check->createToken($result[0]), $result[0], $result[1], $data_qd)->send();die;
        } else {
            echo '获取session_key失败！';
        }
    }

    /**
     * 设置安全密码
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function setSecurityPassWord() {
        $input = input();
        $validate = new Validate([
            ['id', 'require', 'id不能为空'],
            ['security_password', 'require', '安全密码不能为空'],
        ]);
        if(!$validate->check($input))
        {
            returnJson(-1001,  $validate->getError())->send();die;
        }

        $id = $input['id'];
        $security_password = $input['security_password'];
        $model = new HouseKeeper();

        $detail = $model->detail($id);
        if (!empty($detail['security_password'])) {
            returnJson(-2050,'已设置过安全密码')->send();die;
        }

        $data['se_key'] = rand(100000, 999999);
        $data['security_password'] = md5($security_password . $data['se_key']);
        $model->m_update($id, $data);
        returnJson(200,'操作成功')->send();die;
    }

    /**
     * @param $data
     * @return int|string
     */
    private function insert($data) {
        $model = new HouseKeeper();
        $uniqueness = $model->uniqueness($data['tel']);
        if (!$uniqueness) {
            $model->m_insert($data);
            return [$model->getLastInsID('id'), 1];
        } else {
//            $a['name'] = $data['name'];
//            $a['sex'] = $data['sex'];
//            $a['icon'] = $data['icon'];
            $a['update_time'] = time();
            $model->m_update($uniqueness['id'], $a);
            if (empty($uniqueness['security_password'])) {
                return [$uniqueness['id'], 1];
            } else {
                return [$uniqueness['id'], 2];
            }

        }
    }

    /**
     * 发送验证码
     */
    public function getCode() {
        $input = input();
        $admin_tel = $input['tel'];

        $model = new HouseKeeper();
        $detail = $model->uniqueness($admin_tel);
        if (!empty($detail) && $detail['status'] == 2) {
            returnJson(-2001,"用户被禁用")->send();die;
        }

        $code = rand(1000, 9999);
        $model = new SendSms();
        $model->sendSms($admin_tel, $code);

        $model = new Code();
        $data['admin_tel'] = $admin_tel;
        $data['code'] = $code;
        $data['is_use'] = 2;
        $data['create_time'] = time();
        $data = $model->m_insert($data);
        if ($data) {
            returnJson(200,"成功")->send();die;
        } else {
            returnJson(-2001,"服务器出错")->send();die;
        }
    }

    /**
     * 更新安全密码
     */
    public function editSecurityPassword() {
        $input = input();
        $validate = new Validate([
            ['id', 'require', 'id不能为空'],
            ['tel', 'require', '电话不能为空'],
            ['verification_code', 'require', '验证码不能为空'],
//            ['security_password', 'require', '安全密码不能为空'],
            ['token', 'require', 'token不能为空'],
        ]);
        if(!$validate->check($input))
        {
            returnJson(-1001,  $validate->getError())->send();die;
        }

        $id = $input['id'];
        $tel = $input['tel'];
        $code = $input['verification_code'];
        $security_pass = $input['security_password'];
        $this->is_prohibit($id);

        /**
         * 验证手机号是否正确
         */
        $model = new HouseKeeper();
        $detail = $model->detail($id);
        if ($detail['tel'] != $tel) {
            returnJson(-1010,"请输入已绑定的手机号码")->send();die;
        }
        $se_key = $detail['se_key'];

        /**
         * 验证验证码
         */
        $model = new Code();
        $detail = $model->detailtel($tel);
        if (empty($detail)) {
            returnJson(-2010,"请先发送验证码")->send();die;
        }
        if ((time() - $detail['create_time']) > (30 * 60)) {
            returnJson(-2010,"验证码过期")->send();die;
        }
        if ($detail['is_use'] == 1) {
            returnJson(-2010,"验证码已被使用")->send();die;
        }
        if ($detail['code'] !== $code) {
            returnJson(-2011,"验证码错误")->send();die;
        }
        $data['is_use'] = 1;
        $model->m_update($detail['code_id'], $data);
        unset($data['is_use']);

        /**
         * 更新安全密码
         */
        $model = new HouseKeeper();
        $data = ['security_password'=>md5($security_pass . $se_key)];
        $model->m_update($id, $data);

        returnJson(200,"成功")->send();die;
    }

    /**
     * 修改性别
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function editSex() {
        $input = input();
        $validate = new Validate([
            ['id', 'require', 'id不能为空'],
            ['sex', 'require', '性别不能为空'],
            ['token', 'require', 'token不能为空'],
        ]);
        if(!$validate->check($input))
        {
            returnJson(-1001,  $validate->getError())->send();die;
        }

        $sex = $input['sex'];
        $id = $input['id'];
        $this->is_prohibit($id);

        $model = new HouseKeeper();
        $data = ['sex'=>$sex];
        $model->m_update($id, $data);

        /**
         * 修改租客性别
         */
        $model = new TenantManagement();
        $detail = $model->detailKeeper($id);
        if ($detail !== null) {
            $model->m_update($detail['tenant_id'], ['tenant_sex'=>$sex]);
        }

        returnJson(200,"成功")->send();die;
    }

    /**
     * 编辑手机号
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function editTel() {
        $input = input();
        $validate = new Validate([
            ['id', 'require', 'id不能为空'],
//            ['security_password', 'require', '安全密码不能为空'],
            ['tel', 'require', '电话号码不能为空'],
            ['verification_code', 'require', '验证码不能为空'],
            ['token', 'require', 'token不能为空'],
        ]);
        if(!$validate->check($input))
        {
            returnJson(-1001,  $validate->getError())->send();die;
        }

        $id = $input['id'];
        $tel = $input['tel'];
        $code = $input['verification_code'];
        $security_password = $input['security_password'];
        $model_h = new HouseKeeper();
        $model_c = new Code();
        $model_t = new TenantManagement();
        $this->is_prohibit($id);

        /**
         * 验证手机号是否被其他用户使用
         */
        if ($model_h->uniqueness($tel)) {
            returnJson(-1010,  '手机号码已被使用，请重新输入!')->send();die;
        }

        /**
         * 验证安全密码是否正确
         */
        $detail = $model_h->detail($id);
        if ($detail['security_password'] != md5($security_password . $detail['se_key'])) {
            returnJson(-1010,  '安全密码错误，请重新输入!')->send();die;
        }

        /**
         * 验证手机号是否相同
         */
        if ($detail['tel'] == $tel) {
            returnJson(-1010,  '手机号与之前绑定的手机号相同!')->send();die;
        }

        /**
         * 验证验证码
         */
        $detail = $model_c->detailtel($tel);
        if (empty($detail)) {
            returnJson(-2010,"请先发送验证码")->send();die;
        }
        if ((time() - $detail['create_time']) > (30 * 60)) {
            returnJson(-2010,"验证码过期")->send();die;
        }
        if ($detail['is_use'] == 1) {
            returnJson(-2010,"验证码已被使用")->send();die;
        }
        if ($detail['code'] !== $code) {
            returnJson(-2011,"验证码错误")->send();die;
        }
        $data['is_use'] = 1;
        $model_c->m_update($detail['code_id'], $data);
        unset($data['is_use']);

        /**
         * 修改手机号
         */
        $data = ['tel'=>$tel];
        $model_h->m_update($id, $data);

        /**
         * 修改租户手机号
         */
        $detail = $model_t->detailKeeper($id);
        if ($detail !== null) {
            $model_t->m_update($detail['tenant_id'], ['tenant_tel'=>$tel]);
        }
        returnJson(200,"成功")->send();die;
    }

    /**
     * 修改名称
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function editName() {
        $input = input();
        $validate = new Validate([
            ['id', 'require', 'id不能为空'],
            ['name', 'require', '名称不能为空'],
            ['token', 'require', 'token不能为空'],
        ]);
        if(!$validate->check($input))
        {
            returnJson(-1001,  $validate->getError())->send();die;
        }

        $id = $input['id'];
        $name = $input['name'];
        $this->is_prohibit($id);

        $model = new HouseKeeper();
        $data = ['name'=>$name];
        $model->m_update($id, $data);

        /**
         * 修改租客名称
         */
        $model = new TenantManagement();
        $detail = $model->detailKeeper($id);
        if ($detail !== null) {
            $model->m_update($detail['tenant_id'], ['tenant_name'=>$name]);
        }

        returnJson(200,"成功")->send();die;
    }

    /**
     * 编辑头像
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function editIcon() {
        $input = input();
        $validate = new Validate([
            ['id', 'require', 'id不能为空'],
            ['icon', 'require', '头像不能为空'],
            ['token', 'require', 'token不能为空'],
        ]);
        if(!$validate->check($input))
        {
            returnJson(-1001,  $validate->getError())->send();die;
        }

        $id = $input['id'];
        $icon = "https://" . $_SERVER['SERVER_NAME'] . $input['icon'];
        $this->is_prohibit($id);

        $model = new HouseKeeper();
        $data = ['icon'=>$icon];
        $model->m_update($id, $data);
        returnJson(200,"成功")->send();die;
    }

    /**
     * 设置时的信息
     * @throws \think\Exception
     */
    public function setting() {
        $input = input();
        $validate = new Validate([
            ['id', 'require', 'id不能为空'],
        ]);
        if(!$validate->check($input))
        {
            returnJson(-1001,  $validate->getError())->send();die;
        }

        $id = $input['id'];
        $model = new HouseKeeper();
        $this->is_prohibit($id);

        $detail = $model->detail($id);
        returnJson(200,"成功", $detail)->send();die;
    }

    /**
     * 判断是否被禁用
     */
    private function is_prohibit($id) {
        $model = new HouseKeeper();
        $detail = $model->detail($id);
        if ($detail['status'] == 3) {
            returnJson(-3001,"用户不存在")->send();die;
        } elseif ($detail['status'] == 2) {
            returnJson(-3000,"用户被禁用")->send();die;
        } else {

        }
    }
}